package com.suredy.app.ctrl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseFlowCtrl;
import com.suredy.security.model.User;
import com.suredy.security.service.UserSrv;

public class AppBaseCtrl extends BaseFlowCtrl {

	@Autowired
	private UserSrv userSrv;

	@SuppressWarnings("unchecked")
	protected List<String> getRoleCodesFromSession() {
		Object roles = this.getSessionAttribute(Constants.SESSION_USER_ROLES);

		if (roles == null) {
			roles = this.getRoleCodesFromDB();

			if (roles == null)
				roles = new ArrayList<String>(0);

			this.setSessionAttribute(Constants.SESSION_USER_ROLES, roles);
		}

		return (List<String>) roles;
	}

	private List<String> getRoleCodesFromDB() {
		User user = this.getUser();

		if (user == null)
			return null;

		List<String> tmp = this.userSrv.getPermissions(user.getUniqueCode());

		if (tmp == null)
			return null;

		List<String> roles = new ArrayList<String>();

		for (String code : tmp) {
			if (roles.contains(code))
				continue;

			roles.add(code);
		}

		return roles.isEmpty() ? null : roles;
	}

}
